class Work < ActiveRecord::Base
  belongs_to :ac_type
  has_many :results
  belongs_to :author
  has_many :flash_vars, :conditions => "space_type_id is not null"
  has_many :youku_and_tudou, :class_name => "FlashVar", :conditions => "space_type_id in (4,6)"
  validates_uniqueness_of :wid, :message => 'wid same'
  validates_presence_of :wid, :message => 'wid is null'
  #validates_presence_of :cdate, :message => 'cdate is null'
  @@info_key = nil

  def self.get_info_key
    @@info_key ||= Key.first(:conditions => ["app_id = ?", APP_ID]).sec_key rescue nil
  end

  #options:
  def get_info options={}
    url = "http://api.bilibili.tv/view?type=xml&appkey=#{Work.get_info_key}&id=#{wid}"
    page = get_info_page url
    info = page.root
    unless info
      print " #{page.to_s} "
      self.update_attribute(:status, 2) if page.to_s == "error"
      return
    end
    if info.get_elements("code").first && info.get_elements("code").first.text == "-403"
      puts " -403 "
      return
    end
    if info.get_elements("code").first && info.get_elements("code").first.text == "-404"
      puts " -404 "
      return
    end
    #name
    work_name = info.get_elements("title").first.text.gsub('&amp;', '&').gsub('&quot;', '"')
    work_pic_path = info.get_elements("pic").first.text
    work_part_count = info.get_elements("pages").first.text
    if self.part_count.nil? || self.part_count < work_part_count.to_i
      self.update_attributes :name => work_name, :pic_path => work_pic_path, :part_count => work_part_count
    else
      self.update_attributes :name => work_name, :pic_path => work_pic_path
    end
  end

  def get_author_type_info
     require 'net/http/persistent'
     url = "http://#{BILI_PATH}/video/av#{wid}/"
     @http ||= Net::HTTP::Persistent.new(nil, (PROXY ? URI.parse(PROXY) : nil))
      s = Timeout.timeout(10, ThreadError){@http.request(URI.parse(url), Net::HTTP::Get.new(url, {'Cookie' => COOK}))}
      page = Nokogiri::HTML(s.plain_body.delete("\0"), nil, 'utf-8')
     begin
      author_mid_script = page.search("script").detect{|sc| sc.get_attribute("src") && sc.get_attribute("src").split('&mid=').length > 1}
      author_mid = author_mid_script.get_attribute("src").split('&mid=').last
      usname = page.css("div.usname")
      login_name = nil
      nick_name = nil
      unless usname.empty?
        login_name =  page.css("div.msggo").search("a").first.get_attribute("href").split('?uid=').last
        nick_name =  usname.text
      end
      author = Author.find_by_mid author_mid
      if author
        author.update_attribute :nick_name, nick_name if nick_name
      else
        author = Author.create! :login_name =>  login_name, :nick_name => nick_name, :mid => author_mid
      end
      self.update_attribute :author_id, author.id
    #type
      tminfo = page.css("div.tminfo")
      type_name = tminfo.text.split('>')[1].delete!(' ')
      t = AcType.find_by_name type_name
	    is_yule = [19, 20, 21, 22].include?(self.ac_type_id)
      self.update_attribute :ac_type_id, t.id if t
	    if is_yule && ![19, 20, 21, 22].include?(self.ac_type_id)
	      ps = PStore.new("#{Rails.root}/config/space_fix_cache")
		    ps.transaction do
	        ps[self.wid] = 1
	      end
      end
     rescue
	   if page.search("script").to_s.include?("你输入的参数有误")
	     self.update_attribute(:status, 2)
		 puts "delete!"
	   elsif page.search("h3").to_s.include?("你没有权限浏览")
		 puts " tuihui!"
       else		 
         puts page.to_s
       end
    end
  end

  def show_space_info ent=false
    if ent
      youku_and_tudou.collect{|fv| fv.space_type.name}.uniq.join('|')
    else
      flash_vars.collect{|fv| fv.space_type.name}.uniq.join('|')
    end
  end

  def get_info_page uri, i = 1, page = nil
    require 'rexml/document'
    while true
      @http ||= Net::HTTP::Persistent.new(nil, (PROXY ? URI.parse(PROXY) : nil))
      begin
        s = Timeout.timeout(10){@http.request(URI.parse(uri), Net::HTTP::Get.new(uri, {'Cookie' => COOK}))}
        if s.plain_body.empty?
          print " empty "
          sleep 2
        else
          return REXML::Document.new(s.plain_body)
        end
      rescue TimeoutError
        @http.shutdown
        @http = nil
        p $!
      end
    end
  end

  def self.get_vid page
    space_type_name = page.text("from")
    vid = page.text("vid")
    if space_type_name
    space_type = SpaceType.find_by_name space_type_name
    space_type ||= SpaceType.create :name =>space_type_name, :code => space_type_name
    else
      space_type = nil
    end
    return space_type, vid
  end

  #是否参与总分排名
  def is_in_rank?
    !([25,26].include? ac_type_id)
  end
end
